﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace iTunesUpdater
{
	public partial class FileList : UserControl
	{
		public FileList() {
			InitializeComponent();
		}

		public bool UseGroups {
			get { return listView1.ShowGroups; }
			set {
				listView1.ShowGroups = value;
				flagForEncodingToolStripMenuItem.Visible = value;
			}
		}

		private string[] watchFolders;
		public string WatchFolders {
			get {
				if (watchFolders == null)
					return null;

				return string.Join(";", watchFolders);
			}
			set {
				if (string.IsNullOrEmpty(value))
					watchFolders = null;
				else
					watchFolders = value.Split(';');
			}
		}

		private string[] extensions;
		public string Extensions {
			get {
				if (extensions == null)
					return null;

				return string.Join(";", extensions);
			}
			set {
				if (string.IsNullOrEmpty(value))
					extensions = null;
				else
					extensions = value.Split(';');
			}
		}

		string FileBeingTranscoded;
		public void RefreshList() {
			if (InvokeRequired)
				Invoke(new MethodInvoker(RefreshList));
			else {
				listView1.Items.Clear();

				if (watchFolders == null)
					return;

				FileBeingTranscoded = Transcoder.CurrentFile;

				foreach (string folder in watchFolders) {
					try {
						foreach (string ext in extensions) {
							DirectoryInfo dir = new DirectoryInfo(folder);
							FileInfo[] files = dir.GetFiles(ext, SearchOption.AllDirectories);
							foreach (FileInfo file in files) {
								AddItem(file);
							}
						}
					}
					catch (Exception ex) {
						MessageBox.Show("Can't add folder " + folder + "\r\n" + ex.Message);
					}
				}
			}
		}

		public void AddItem(FileInfo file) {
			ListViewItem item = listView1.Items.Add(file.Name);
			item.Tag = file.FullName;

			if (!UseGroups) {
				item.Group = null;
			}
			else {
        if (Path.GetFileNameWithoutExtension(file.Name) == Path.GetFileNameWithoutExtension(FileBeingTranscoded))
					item.Group = listView1.Groups["grpEncoding"];
				else if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
					item.Group = listView1.Groups["grpRecording"];
				else if ((file.Attributes & FileAttributes.Archive) == FileAttributes.Archive)
					item.Group = listView1.Groups["grpReady"];
				else
					item.Group = listView1.Groups["grpEncoded"];
			}
		}

		List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
		public void StartWatching() {
			StopWatching();
			foreach (string folder in watchFolders) {
				FileSystemWatcher w = new FileSystemWatcher(folder);
				w.IncludeSubdirectories = true;
				//w.Changed += new FileSystemEventHandler(w_Changed);
				w.Created += new FileSystemEventHandler(w_Changed);
				w.Deleted += new FileSystemEventHandler(w_Changed);
				w.EnableRaisingEvents = true;
				watchers.Add(w);
				timer1.Enabled = true;
			}
			RefreshList();
		}

		public void StopWatching() {
			timer1.Enabled = false;
			foreach (var w in watchers) {
				w.Changed -= w_Changed;
			}
		}

		void w_Changed(object sender, FileSystemEventArgs e) {
			RefreshList();
		}

		private void listView1_SizeChanged(object sender, EventArgs e) {
			if (!DesignMode)
				colName.Width = ClientSize.Width - ColSize.Width - 5;
		}

		public string[] SelectedItems {
			get {
				string[] ret = new string[listView1.SelectedItems.Count];
				for (int i = 0; i < listView1.SelectedItems.Count; i++) {
					ret[i] = listView1.SelectedItems[i].Text;
				}
				return ret;
			}
		}

		public string[] SelectedFileNames {
			get {
				string[] ret = new string[listView1.SelectedItems.Count];
				for (int i = 0; i < listView1.SelectedItems.Count; i++) {
					ret[i] = (string)listView1.SelectedItems[i].Tag;
				}
				return ret;
			}
		}

		private void RefreshButton_Click(object sender, EventArgs e) {
			RefreshList();
		}

		private void timer1_Tick(object sender, EventArgs e) {
			RefreshList();
		}

		public void DeleteSelectedItems() {
			if (SelectedFileNames.Length == 0)
				return;

			if (MessageBox.Show("Delete these files?\r\n" + string.Join("\r\n", SelectedFileNames), "Delete files", MessageBoxButtons.YesNo) == DialogResult.Yes) {
				foreach (string file in SelectedFileNames) {
					try {
						File.Delete(file);
					}
					catch (Exception ex) {
						MessageBox.Show("Error deleting " + file + ":" + ex.Message);
					}
				}
			}
		}

		private void flagForEncodingToolStripMenuItem_Click(object sender, EventArgs e) {
			ToggleEncodeFlag(SelectedFileNames);
			RefreshList();
		}

		/// <summary>
		/// Toggle the "ready to be encoded" status of a set of files. Files already set to encode 
		/// will be flagged as finished. Files flagged finished will be set to encode again.
		/// </summary>
		/// <param name="files">filenames of the files to toggle</param>
		private void ToggleEncodeFlag(string[] files) {
			foreach (string file in files) {
				FileInfo fi = new FileInfo(file);
				fi.Attributes = fi.Attributes ^ FileAttributes.Archive;
			}
		}

		private void deleteToolStripMenuItem_Click(object sender, EventArgs e) {
			DeleteSelectedItems();
		}
	}
}
